package com.example.simon.greettophone;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.microsoft.cognitiveservices.speechrecognition.MicrophoneRecognitionClientWithIntent;
import com.microsoft.cognitiveservices.speechrecognition.SpeechRecognitionServiceFactory;
import com.microsoft.cognitiveservices.speechrecognition.DataRecognitionClient;
import com.microsoft.cognitiveservices.speechrecognition.ISpeechRecognitionServerEvents;
import com.microsoft.cognitiveservices.speechrecognition.MicrophoneRecognitionClient;
import com.microsoft.cognitiveservices.speechrecognition.RecognitionResult;
import com.microsoft.cognitiveservices.speechrecognition.RecognitionStatus;
import com.microsoft.cognitiveservices.speechrecognition.SpeechRecognitionMode;

public class MainActivity extends AppCompatActivity implements ISpeechRecognitionServerEvents {

//    int m_waitSeconds = 0;
//    DataRecognitionClient m_dataClient = null;
MicrophoneRecognitionClientWithIntent m_micClient = null;
    FinalResponseStatus isReceivedResponse = FinalResponseStatus.NotReceived;
    TextView mResultDisplay;
//    private SpeechRecognitionMode m_recoMode;
//    Button m_startButton = (Button) findViewById(R.id.startBut);

    public enum FinalResponseStatus {NotReceived, OK, Timeout}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResultDisplay = (TextView) findViewById(R.id.receive);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int menuItemThatWasSelected = item.getItemId();
        if(menuItemThatWasSelected == R.id.action_record){
            Context context = MainActivity.this;
            String message = "Search clicked.";
            Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
            LetsRecognise();//识别之
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPartialResponseReceived(String s) {
        Log.i("partial", "onPartialResponseReceived: " + s);
    }

    @Override
    public void onFinalResponseReceived(RecognitionResult response) {
        Log.i("result", "onFinalResponseReceived: ");
        boolean isFinalDictationMessage = SpeechRecognitionMode.ShortPhrase
                == SpeechRecognitionMode.LongDictation &&
                (response.RecognitionStatus == RecognitionStatus.EndOfDictation ||
                        response.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout);

        if (null != this.m_micClient && isFinalDictationMessage) {
            // we got the final result, so it we can end the mic reco.  No need to do this
            // for dataReco, since we already called endAudio() on it as soon as we were done
            // sending all the data.
            this.m_micClient.endMicAndRecognition();
        }

        if (isFinalDictationMessage) {

            this.isReceivedResponse = FinalResponseStatus.OK;
        }

        if (!isFinalDictationMessage) {
            mResultDisplay.append("********* Final n-BEST Results *********");
            for (int i = 0; i < response.Results.length; i++) {
                mResultDisplay.append("[" + i + "]" + " Confidence=" + response.Results[i].Confidence +
                        " Text=\"" + response.Results[i].DisplayText + "\"");
            }
        }
    }

    @Override
    public void onIntentReceived(String s) {
        Log.i("intent", "onIntentReceived: " + s);
        mResultDisplay.append(s);
    }

    @Override
    public void onError(int i, String s) {
        Log.e("error", "ErroCode: " + i + ",Error:" + s);
        mResultDisplay.append(s);
    }

    @Override
    public void onAudioEvent(boolean b) {
        String info = null;
        if (b) {
            info = "on";
        } else {
            info = "off";
            m_micClient.endMicAndRecognition();
        }
        Log.i("auodio", "onAudioEvent: " + info);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    void LetsRecognise() {
        String language = this.getString(R.string.location);
        String subscriptionKey = this.getString(R.string.subscription_key);
        String luisAppID = this.getString(R.string.luisAppID);
        String luisSubscriptionID = this.getString(R.string.luisSubscriptionID);

        if (null == m_micClient) {

            MicrophoneRecognitionClientWithIntent intentMicClient;
            intentMicClient = SpeechRecognitionServiceFactory.createMicrophoneClientWithIntent(this,
                    language,
                    (ISpeechRecognitionServerEvents) this,
                    subscriptionKey,
                    luisAppID,
                    luisSubscriptionID);
            m_micClient = intentMicClient;
        }
        m_micClient.setAuthenticationUri(getString(R.string.authenticationUri));
        m_micClient.startMicAndRecognition();
    }

}
